﻿using mozhi.smarterp.BasicData.Enums;
using mozhi.smarterp.BasicData.ExpenseItems.Repositories;
using System;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;
using Volo.Abp.Guids;

namespace mozhi.smarterp.BasicData.ExpenseItems.Services
{
    public class ExpenseItemManager :  DomainService
    {
        private IExpenseItemRepository _repository;
        private IGuidGenerator _guidGenerator;

        public ExpenseItemManager(IExpenseItemRepository repository, IGuidGenerator guidGenerator)
        {
            _repository = repository;
            _guidGenerator = guidGenerator;
        }

        public async Task<ExpenseItem> GetAysnc(Guid? id, string code, string name, ExpenseItemType type,  bool activated)
        {
            var matchCount = await _repository.GetCountAsync(code, null , id) + await _repository.GetCountAsync(null, name, id);

            if (matchCount > 0)
                throw new UserFriendlyException("编码或者名称已经存在", "100000");

            ExpenseItem expenseItem;

            if (id.HasValue)
            {
                expenseItem = await _repository.GetAsync(id.Value);
                expenseItem.Change(code, name, type, activated);
            }
            else
                expenseItem = new ExpenseItem(_guidGenerator.Create(), code, name, type, activated);

            return expenseItem;
        }
    }
}
